package com.shujia.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

public class Code01ZkCon {
    public static void main(String[] args) throws IOException, InterruptedException {

        /*
            链接Zookeeper => 操作对象
            public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
            connectString 表示链接信息
            watcher:监控当前链接的线程,观察其状态，并需要重写其process处理函数
         */

        System.out.println("zookeeper正在实例化..");

        /**
         * zookeeper正在实例化..
         * Zookeeper实例化完成..
         * process函数执行了...
         * process函数执行了...
         * Zookeeper关闭了..
         *
         *  Watcher的匿名对象创建后，对应process函数会通过多线程方式去执行
         *
         *  Watcher用于监控当前链接变化信息，
         *          那么当Zookeeper连接上，那么状态变更会执行一次
         *          那么当Zookeeper关闭，那么状态变更也会执行一次
         *
         */

        ZooKeeper zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181",
                15 * 1000,
                new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        System.out.println("process函数执行了...");
                    }
                }
        );

        System.out.println("Zookeeper实例化完成..");
        zooKeeper.close();
        System.out.println("Zookeeper关闭了..");
    }

}
